<?php
namespace app\admin\model\sys;

use app\common\model\Base;
use think\Model;
use think\Facade\Db;

class AuthRule extends Base
{

    /**
     * 新增前，对数据进行特殊处理
     * @param Model $model
     * @return mixed|void
     */
    public static function onBeforeInsert(Model $model)
    {
        $model->icon = $model->icon?$model->icon:'fa fa-adjust';
        if(strpos(trim($model->href,'/'),'admin/')===false){
            $model->href = 'admin/'.trim($model->href,'/');
        }
        return true;
    }
    /**
     * 更新前，对数据进行特殊处理
     * @param Model $model
     * @return mixed|void
     */
    public static function onBeforeUpdate(Model $model)
    {
        $model->icon = $model->icon?$model->icon:'fa fa-adjust';
        if(strpos(trim($model->href,'/'),'admin/')===false){
            $model->href = 'admin/'.trim($model->href,'/');
        }
        return true;
    }

    /**
     * 权限设置选中状态
     * @return array
     */
    public static function authChecked($cate , $pid = 0,$rules){
        $list = [];
        $rulesArr = explode(',',$rules);
        foreach ($cate as $v){
            if ($v['pid'] == $pid) {
                $v['spread'] = true;
                if(self::authChecked($cate,$v['id'],$rules)){
                    $v['children'] =self::authChecked($cate,$v['id'],$rules);
                }else{
                    if (in_array($v['id'], $rulesArr)) {
                        $v['checked'] = true;
                    }
                }
                $list[] = $v;
            }
        }
        return $list;
    }
    /**
     * 权限多维转化为二维
     * @return array
     */
    public static function authNormal($cate){
        $list = [];
        foreach ($cate as $v){
            $list[]['id'] = $v['id'];
            if (!empty($v['children'])) {
                $listChild =  self::authNormal($v['children']);
                $list = array_merge($list,$listChild);
            }
        }
        return $list;
    }
    /**
     * 检查用户权限
     */
    public static function checkAuth($url)
    {
        $group = session('admin.group_id');

        // id为1的是超级管理员，或者角色为1的，拥有最高权限
        if (session('admin.id') == '1' || $group == '1') {
            return true;
        }

        $hrefId = Db::name('auth_rule')->where('href',$url)->value('id');

        $map['a.id'] = session('admin.id');
        $rules=Db::name('admin')->alias('a')
            ->join('auth_group ag','a.group_id = ag.id','left')
            ->where($map)
            ->value('ag.rules');
        //用户权限规则id
        $adminRules = explode(',',$rules);


        if($hrefId){
            // 不在权限里面，并且请求为post
            if(!in_array($hrefId,$adminRules)){
                return false;
            }
        }
        return true;
    }
}
